from flask import (
    Blueprint, json
)
from blemesh import db, util
from .mesh import login_request
from .error import error_handle
import threading

light = db.Light()

bp = Blueprint('light', __name__, url_prefix='/light')
mutex = threading.Lock()
#light = db.light()

@bp.route('/light_list/',methods=['POST'])
@error_handle
@login_request
def light_list(user_id, req, res):
    meshid = req['meshid']
    type = req['type']
    dbresult = light.lights_of_mesh(meshid)
    res['lights'] = []
    if dbresult:
        length = len(dbresult)
        for i in range(length):
            tmp = dbresult[i]
            lighti = {
                'id': tmp['id'],
                'name': tmp['name'],
                'cold': tmp['cold'],
                'warm': tmp['warm'],
                'red': tmp['red'],
                'green': tmp['green'],
                'blue': tmp['blue'],
                'meshid': tmp['m_id'],
                'deviceaddress': tmp['device_address'],
                'devicekey': tmp['device_key'],
                'state': tmp['switch']
            }
            lighti["uuid"] =tmp['ios_uuid'] if type=="ios" else tmp['android_uuid'];
            print("该灯的id值：", tmp['id'])
            print ("该灯的switch值：",tmp['switch'])
            res['lights'].append(lighti)
    res['code'] = 0
    res['msg'] = "获取该网中的灯列表成功!"
    return json.dumps(res)


@bp.route('/get_node_addr_in_mesh/',methods=['POST'])
@error_handle
@login_request
def get_node_addr_in_mesh(user_id, req, res):
    meshid = req['meshid']
    # 获取地址到更新地址要加锁
    mutex.acquire()
    dbresult = light.get_node_addr(meshid)
    if(dbresult):
        node_address = dbresult['node_address']
        new_node_address = util.hexstr_to_int(node_address) + 1
        new_node_address = util.int_to_hexstr(new_node_address, 4)
        dbresult = light.update_node_addr(meshid, new_node_address)
        if(dbresult):
            res['device_address'] = node_address
            res['code'] = 0
            res['msg'] = "获取最新node_address成功！"
        else:
            res['code'] = 1315
            res['msg'] = "获取最新node_address时数据库出错!"
    else:
        res['msg'] = "获取最新node_address时数据库出错!"
    mutex.release()
    return json.dumps(res)


@bp.route('/add_light_into_mesh/',methods=['POST'])
@error_handle
@login_request
def add_light_into_mesh(user_id, req, res):
     print("req=========================:",req)
     name = req['name']
     cold = req['cold']
     warm = req['warm']
     red = req['red']
     green = req['green']
     blue = req['blue']
     meshid = req['meshid']
     deviceaddress = req['deviceaddress']
     uuid = req['uuid']
     devicekey = req['devicekey']
     type = req['type']
     dbresult = light.add_light_mesh( name,type, cold, warm, red, green, blue, meshid, deviceaddress, uuid, devicekey)
     if dbresult:
        res['light_id'] = dbresult['id']
        res['code'] = 0
        res['msg'] = "添加灯成功！"
     else:
        res['msg'] = "添加灯时数据库出错!"
     return json.dumps(res)

@bp.route('/delete_light_of_mesh/', methods=['POST'])
@error_handle
@login_request
def delete_light_of_mesh(user_id, req, res):
    lightid = req['lightid']
    meshid = req['meshid']
    #newnetkey = req['newnetkey']
    dbresult1 = light.delete_light_mesh(lightid)
    #dbresult2 = light.update_mesh_netkey(meshid, newnetkey)
    if dbresult1: #and dbresult2:
        res['code'] = 0
        res['msg'] = "删灯出网成功！"
    else:
        res['msg'] = "删灯出网时数据库出错!"
    return json.dumps(res)

@bp.route('/add_light_to_group/',methods=['POST'])
@error_handle
@login_request
def add_light_to_group(user_id, req, res):
     groupid = req['groupid']
     lightid = req['lightid']

     dbresult = light.add_light_to_group(groupid, lightid)
     if dbresult:
        res['code'] = 0
        res['msg'] = "添灯入组成功！"
     else:
        res['msg'] = "添灯入组时数据库出错!"
     return json.dumps(res)

@bp.route('/delete_light_of_group/', methods=['POST'])
@error_handle
@login_request
def delete_light_of_group(user_id, req, res):
    groupid = req['groupid']
    lightid = req['lightid']
    dbresult = light.delete_light_of_group(groupid, lightid)
    if dbresult:
        res['code'] = 0
        res['msg'] = "删灯出组成功！"
    else:
        res['msg'] = "删灯出组时数据库出错!"
    return json.dumps(res)

@bp.route('/change_light/', methods=['POST'])
@error_handle
@login_request
def change_light(user_id, req, res):
    lightid = req['lightid']
    uuid = req['uuid']
    meshid = req['meshid']
    newnetkey = req['newnetkey']
    dbresult1 = light.update_light_uuid(lightid, uuid)
    dbresult2 = light.update_mesh_netkey(meshid, newnetkey)
    if dbresult1 and dbresult2:
        res['code'] = 0
        res['msg'] = "换灯成功！"
    else:
        res['msg'] = "换灯时数据库出错!"
    return json.dumps(res)

@bp.route('/edit_light/', methods=['POST'])
@error_handle
@login_request
def edit_light(user_id, req, res):
    lightid = req['lightid']
    cold = req['cold']
    warm = req['warm']
    red = req['red']
    green = req['green']
    blue = req['blue']
    dbresult = light.edit_light(lightid, cold, warm, red, green, blue)

    if dbresult:
        res['code'] = 0
        res['msg'] = "编辑灯信息成功！"
    else:
        res["code"] = 1314
        print(">>>>>>>>>>>>>>>> edit light date error <<<<<<<<<<<<<<<")
        print(str(res))
        res['msg'] = "编辑灯信息时数据库出错!"
    return json.dumps(res)

@bp.route('/rename_light/', methods=['POST'])
@error_handle
@login_request
def rename_light(user_id, req, res):
    lightid = req['lightid']
    name = req['name']
    dbresult = light.rename_light(lightid, name)
    if dbresult:
        res['code'] = 0
        res['msg'] = "修改灯名成功！"
    else:
        res['msg'] = "修改灯名时数据库出错!"
    return json.dumps(res)

@bp.route('/open_light/', methods=['POST'])
@error_handle
@login_request
def open_light(user_id, req, res):
    lightid = req['lightid']
    dbresult = light.open_light(lightid)
    if dbresult:
        res['code'] = 0
        res['msg'] = "开灯成功！"
    else:
        res['code'] = 1
        res['msg'] = "开灯时数据库出错!"
    return json.dumps(res)

@bp.route('/off_light/', methods=['POST'])
@error_handle
@login_request
def off_light(user_id, req, res):
    lightid = req['lightid']
    dbresult = light.off_light(lightid)
    if dbresult:
        res['code'] = 0
        res['msg'] = "开灯成功！"
    else:
        res['msg'] = "开灯时数据库出错!"
    return json.dumps(res)



